package com.settlement.system.model.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.settlement.system.common.base.BaseEntity;
import com.settlement.system.common.util.NumberUtils;
import com.settlement.system.common.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 天猫资金流水
 * </p>
 *
 * @author huangrensen
 * @since 2024-04-25
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TmFundFlow extends BaseEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    private static final Logger logger = LoggerFactory.getLogger(TmFundFlow.class);

    @TableId(value = "id")
    private String id;


    /**
     * 账务流水号
     */
    private String financeNo;

    // 店铺id
    private Long storeId;
    @TableField(exist = false)
    private String storeName;

    /**
     * 业务流水号
     */
    private String businessNo;


    /**
     * 原商户订单号
     */
    private String originalSellerOrderNo;


    /**
     * 商户订单号
     */
    private String sellerOrderNo;


    /**
     * 商品名称
     */
    private String productName;


    /**
     * 发生时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime orderTime;
    @TableField(exist = false)
    private LocalDateTime startOrderTime;
    @TableField(exist = false)
    private LocalDateTime endOrderTime;


    /**
     * 对方账号
     */
    private String buyerAcount;


    /**
     * 收入金额
     */
    private BigDecimal incomeAmount = BigDecimal.ZERO;


    /**
     * 支出金额
     */
    private BigDecimal payAmount = BigDecimal.ZERO;


    /**
     * 账户余额
     */
    private BigDecimal balance = BigDecimal.ZERO;


    /**
     * 交易渠道
     */
    private String channel;


    /**
     * 业务类型
     */
    private String businessType;

    /**
     * 备注
     */
    private String remark;

    // 是否匹配到商户订单号
    @TableField(exist = false)
    private boolean findFlag = false;

    @TableField(exist = false)
    private String tableName;

    @TableField(exist = false)
    private String billMonth;


    public void formatSellerOrderNo() {
        // 提取商户订单号
        String remark;
        if (Objects.isNull(this.remark)) {
            remark = "";
        } else {
            remark = this.remark.strip().replaceAll("［", "[")
                    .replaceAll("\t", "")
                    .replaceAll("\"", "")
                    .replaceAll("：", ":")
                    .replaceAll("（", "(")
                    .replaceAll("）", ")");
        }
        String[] splitData;
        Pattern pattern;
        Matcher matcher;
        try{
            // 代扣返点积分 取备注中最后19位单号
            if (remark.contains("代扣返点积分") && remark.length() > 19) {
                this.sellerOrderNo = remark.substring(remark.length() - 19);
            } else if (remark.contains("代扣款") && remark.contains("天猫佣金") && remark.contains("赠品") && remark.length() > 38) {
                // 天猫资金流水的备注.contains("代扣款")&&天猫资金流水的备注.contains("天猫佣金")&&天猫资金流水的备注.contains("赠品")
                // 代扣款-天猫佣金-赠品 备注中从19位开始取19个字符
                this.sellerOrderNo = remark.substring(18, 37);
            } else if (remark.contains("保险承保-卖家版运费险保费收取")) {
                // 保险承保-卖家版运费险保费收取 备注中，取最后19位单号
                this.sellerOrderNo = remark.substring(remark.length() - 19);
            } else if (remark.contains("保险承保-天猫海外退货险保费收取") && remark.contains("[") && remark.contains("]")) {
                // 保险承保-天猫海外退货险保费收取 备注中，后面中括号内的单号
                this.sellerOrderNo = remark.substring(remark.lastIndexOf("[") + 1, remark.lastIndexOf("]"));
            } else if (remark.contains("保险承保-聚划算运费险保费收取") && remark.length() > 19) {
                // 保险承保-聚划算运费险保费收取 备注中，取最后19位单号
                this.sellerOrderNo = remark.substring(remark.length() - 19);
            } else if (remark.contains("代扣款") && remark.contains("海外零售计划") && remark.contains("供应链管理服务费扣款")) {
                // 代扣款-“海外零售计划”供应链管理服务费扣款 备注中倒数第二个单号
                if (remark.contains("_")) {
                    splitData = remark.split("_");
                    if (splitData.length >= 3) {
                        this.sellerOrderNo = splitData[splitData.length - 2];
                    }
                }
            } else if (remark.contains("保险理赔-天猫海外退货险理赔款") && remark.contains("[") && remark.contains("]")) {
                // 保险理赔-天猫海外退货险理赔款 备注中，后面中括号内的单号
                this.sellerOrderNo = remark.substring(remark.lastIndexOf("[") + 1, remark.lastIndexOf("]"));
            } else if (remark.contains("代扣款") && remark.contains("天猫佣金") && remark.contains("补差价/邮费") && remark.contains("{") && remark.contains("}")) {
                // 代扣款-天猫佣金-补差价/邮费 备注中，大括号内的单号
                this.sellerOrderNo = remark.substring(remark.indexOf("{") + 1, remark.indexOf("}"));
            } else if (remark.contains("保险承保-严选直播运费险保费收取:") && remark.length() > 19) {
                // 保险承保-严选直播运费险保费收取 备注中，取最后19位单号
                this.sellerOrderNo = remark.substring(remark.length() - 19);
            } else if (remark.startsWith("保证金退款") && remark.length() > 19) {
                // 备注中最后19位单号
                this.sellerOrderNo = remark.substring(remark.length() - 19);
            } else if (remark.contains("花呗支付服务费") && this.originalSellerOrderNo.length() > 19) {
                // 花呗支付服务费：商户订单号中最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("代扣款") && remark.contains("天猫佣金") && remark.contains("类目") && !remark.contains("类目系统") && !remark.contains("淘宝联盟") && this.originalSellerOrderNo.length() > 19) {
                // 代扣款 天猫佣金 类目：商户订单号,最后19位单号
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("信用卡支付服务费") && this.originalSellerOrderNo.length() > 19) {
                // 信用卡支付服务费：商户订单号最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("淘宝内容推广服务费") && this.originalSellerOrderNo.length() > 19) {
                // 淘宝内容推广服务费：商户订单号最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("聚划算佣金") && this.originalSellerOrderNo.length() > 19) {
                // 聚划算佣金：商户订单号最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("淘宝客佣金代扣款") && this.originalSellerOrderNo.length() > 19) {
                // 淘宝客佣金代扣款：商户订单号最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("代扣款") && remark.contains("天猫佣金") && remark.contains("类目系统") && !remark.contains("淘宝联盟") && this.originalSellerOrderNo.length() > 19) {
                // 代扣款-天猫佣金-类目系统：商户订单号中最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("品牌新享-首单拉新计划") && this.originalSellerOrderNo.length() > 19) {
                // 品牌新享-首单拉新计划：商户订单号中最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (StringUtils.hasText(this.businessType) && this.businessType.contains("其它") && this.originalSellerOrderNo.length() > 19) {
                // 其他费用：商户订单号中最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("售后退款") && !remark.contains("天猫保证金-充值") && this.originalSellerOrderNo.length() > 19) {
                // 售后退款：商户订单号中最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("信用购分期-保证金退款") && this.originalSellerOrderNo.length() > 19) {
                // 信用购分期-保证金退款：商户订单号中最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (StringUtils.hasText(this.businessType) && this.businessType.contains("交易付款") && this.originalSellerOrderNo.length() > 19) {
                // 交易付款：商户订单号中最后19位
                this.sellerOrderNo = this.originalSellerOrderNo.substring(this.originalSellerOrderNo.length() - 19);
            } else if (remark.contains("保险承保-百亿补贴运费险保费收取") && remark.length() > 19) {
                // 保险承保-百亿补贴运费险保费收取：备注中最后的单号
                this.sellerOrderNo = remark.substring(remark.length() - 19);
            } else if (remark.contains("百亿补贴软件服务费(渠道)") && remark.contains("扣款") && remark.length() > 19) {
                // 百亿补贴软件服务费（渠道）扣款：取备注中的单号
                this.sellerOrderNo = remark.substring(remark.lastIndexOf("(") + 1, remark.lastIndexOf(")"));
            } else if (remark.contains("百亿补贴软件服务费(渠道)") && remark.contains("退款") && remark.length() > 19) {
                // 百亿补贴软件服务费（渠道）退款：取备注中的单号
                this.sellerOrderNo = remark.substring(remark.lastIndexOf("(") + 1, remark.lastIndexOf(")"));
            } else if (remark.contains("天猫佣金-百补订单预收") && remark.length() > 19) {
                // 天猫资金流水的备注.contains("天猫佣金-百补订单预收")：备注中大括号内的单号
                this.sellerOrderNo = remark.substring(remark.indexOf("{") + 1, remark.indexOf("}"));
            } else if (remark.contains("天猫佣金-百补订单预收") && remark.length() > 19) {
                // 天猫资金流水的备注.contains("天猫佣金-百补订单激励前返")：备注中“订单号”后面的单号
                splitData = remark.split("订单号:");
                if (splitData.length > 1) {
                    this.sellerOrderNo = splitData[1].split("\\)")[0];
                }
            } else if (remark.contains("商家集运物流责任货值赔付")) {
                // 天猫资金流水的备注.contains("商家集运物流责任货值赔付")：取商户订单号
                this.sellerOrderNo = this.originalSellerOrderNo;
            } else if (remark.contains("基金代发任务") && remark.contains("代扣款")) {
                // 天猫资金流水的备注.contains("基金代发任务")&&天猫资金流水的备注.contains("代扣款")：备注中，订单编号后面的单号
                pattern = Pattern.compile("订单编号:(\\d+)");
                matcher = pattern.matcher(remark);
                if (matcher.find()) {
                    this.sellerOrderNo = matcher.group(1);
                }
            } else if (remark.contains("大服饰跨境服务增值费") && this.originalSellerOrderNo.length() > 6) {
                // 天猫资金流水的备注.contains("大服饰跨境服务增值费")：商户订单号，从第6位开始取
                this.sellerOrderNo = this.originalSellerOrderNo.substring(5);
            } else if (remark.contains("基础软件服务费") && this.originalSellerOrderNo.length() > 6) {
                // 天猫资金流水的备注.contains("基础软件服务费")：商户订单号，从第6位开始取
                this.sellerOrderNo = this.originalSellerOrderNo.substring(5);
            } else if (remark.contains("天猫提现")) {
                // 天猫资金流水的备注.contains("天猫提现")：商户订单号
                this.sellerOrderNo = this.originalSellerOrderNo;
            } else if (remark.contains("淘宝惠商计划退款")) {
                // 天猫资金流水的备注.contains("淘宝惠商计划退款")：商户订单号
                this.sellerOrderNo = this.originalSellerOrderNo;
            } else if (remark.contains("淘宝惠商计划退款")) {
                // 天猫资金流水的备注.contains("淘宝惠商计划退款")：商户订单号
                this.sellerOrderNo = this.originalSellerOrderNo;
            } else if (remark.contains("售后支付") && StringUtils.hasText(this.businessType) && this.businessType.contains("其它")) {
                // 天猫资金流水的备注contains("售后支付”)&&天猫资金流水的业务类型contains("其它”)：商户订单号第5位开始取
                this.sellerOrderNo = this.originalSellerOrderNo.substring(4);
            } else {
                // 所有情况都不符合，直接取原商户订单号
                this.sellerOrderNo = this.originalSellerOrderNo;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("提取天猫资金流水单号异常，原商户订单号【{}】", this.originalSellerOrderNo);
            this.sellerOrderNo = this.originalSellerOrderNo;
        }
    }

    private static boolean compareDate(LocalDateTime date1, LocalDateTime date2) {
        if (date1 == null && date2 == null) {
            return true;
        }
        if (date1 != null && date1.equals(date2)) {
            return true;
        }
        return false;
    }

    private static boolean compareBigDecimal(BigDecimal value1, BigDecimal value2) {
        if (value1 == null && value2 == null) {
            return true;
        }
        if (Objects.isNull(value2)) {
            value2 = BigDecimal.ZERO;
        }
        if (value1 != null && value1.compareTo(value2) == 0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        TmFundFlow that = (TmFundFlow) o;
        return Objects.equals(financeNo, that.financeNo) && Objects.equals(storeId, that.storeId) && Objects.equals(businessNo, that.businessNo) && Objects.equals(originalSellerOrderNo, that.originalSellerOrderNo) && Objects.equals(sellerOrderNo, that.sellerOrderNo) && Objects.equals(productName, that.productName) && compareDate(orderTime, that.orderTime) && Objects.equals(buyerAcount, that.buyerAcount) && compareBigDecimal(incomeAmount, that.incomeAmount) && compareBigDecimal(payAmount, that.payAmount) && compareBigDecimal(balance, that.balance) && Objects.equals(channel, that.channel) && Objects.equals(businessType, that.businessType) && Objects.equals(remark, that.remark);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), financeNo, storeId, businessNo, originalSellerOrderNo, sellerOrderNo, productName, orderTime, buyerAcount, incomeAmount, payAmount, balance, channel, businessType, remark);
    }

    // 截取长度超出范围的字段
    public void cutString() {
        if (this.remark != null && this.remark.length() > 2000) {
            this.remark = this.remark.substring(0, 2000);
        }
    }

    public static void main(String[] args) {
        /*String remark = "代扣款（扣款用途：基金代发任务。订单编号：2169014882574996688，付款方：浙江天猫技术有限公司，Email：p-tmall-kefupeifu@service.taobao.com）";
        remark = remark.strip().replaceAll("［", "[")
                .replaceAll("\t", "")
                .replaceAll("\"", "")
                .replaceAll("：", ":")
                .replaceAll("（", "(")
                .replaceAll("）", ")");
        Pattern pattern = Pattern.compile("订单编号:(\\d+)");
        Matcher matcher = pattern.matcher(remark);
        if (matcher.find()) {
            String result = matcher.group(1);
            System.out.println(result);
        }*/
        System.out.println("12345678".substring(4));
    }
}
